<?php
namespace App\Api\Fcjd;

use PhalApi\Api;

/**
 * KamiUser接口
 * @desc 读取phone_kami表数据
 */
class KamiUser extends Api {
    public function getRules() {
        return array(
            'getList' => array(
                'username' => array('name' => 'username', 'type' => 'string', 'require' => true, 'desc' => '用户名'),
                'page' => array('name' => 'page', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '页码'),
                'page_size' => array('name' => 'page_size', 'type' => 'int', 'min' => 1, 'max' => 500, 'require' => true, 'desc' => '每页数量'),
                'status' => array('name' => 'status', 'type' => 'int', 'min' => 0, 'max' => 1, 'require' => true, 'desc' => '状态')
            ),
            'assignment' => array(
                'ids' => array('name' => 'ids', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 'require' => true, 'desc' => '数组格式的ID列表'),
                'note' => array('name' => 'note', 'type' => 'string', 'desc' => '备注信息'),
                'user_id' => array('name' => 'user_id', 'type' => 'int', 'desc' => '用户ID'),
            ),
            'used' => array(
                'card_codes' => array('name' => 'card_codes', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 
                'require' => true, 'desc' => '数组格式的ID列表'),
                'phoneIds' => array('name' => 'phoneIds', 'type' => 'array', 'format' => 'explode', 'desc' => '用户ID'),
            ),
            'getUsedList' => array(
                'username' => array('name' => 'username', 'type' => 'string', 'require' => true, 'desc' => '用户名'),
                'page' => array('name' => 'page', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '页码'),
                'page_size' => array('name' => 'page_size', 'type' => 'int', 'min' => 1, 'max' => 500, 'require' => true, 'desc' => '每页数量'),
                'searchKey' => array('name' => 'searchKey', 'require' => false, 'desc' => '查询key'),
            ),
        );
    }

    /**
     * 获取使用kami列表
     * @desc 获取phone_kami表数据
     * @return array items 数据列表
     * @return int total 总记录数
     */
    public function getUsedList() {
        $page = $this->page;
        $pageSize = $this->page_size;
        $searchKey = $this->searchKey;
        $username = $this->username;

        $where = array(
            'username' => $username,
        );
        $select = "card_code,duration_type,used_time,note,mobile";

        if( $searchKey ){
            $json = '%' . $searchKey . '%';
            $where = array(
                'username' => $username,
                '(mobile LIKE? OR card_code)' => array($json, $json),
            );
        }
        
        $total = \PhalApi\DI()->notorm->phone_kami_used->where($where)->count();
        $items = \PhalApi\DI()->notorm->phone_kami_used
            ->select($select)
            ->order('id DESC')
            ->where($where)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->fetchAll();
            
        \PhalApi\DI()->response->addResult('success', true);
        return array('items' => $items, 'total' => $total, 'page' => $page, 'page_size' => $pageSize);
    }

    /**
     * 获取kami列表
     * @desc 获取phone_kami表数据
     * @return array items 数据列表
     * @return int total 总记录数
     */
    public function getList() {
        $page = $this->page;
        $pageSize = $this->page_size;

        $where = array(
            'username' => $this->username,
            'status' => $this->status,
        );
        $select = "card_code,status,duration_type";
        
        $total = \PhalApi\DI()->notorm->phone_kami->where($where)->count();
        $items = \PhalApi\DI()->notorm->phone_kami
            ->select($select)
            ->order('id DESC')
            ->where($where)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->fetchAll();
            
        \PhalApi\DI()->response->addResult('success', true);
        return array('items' => $items, 'total' => $total, 'page' => $page, 'page_size' => $pageSize);
    }
    
    
    /**
     * 分配卡密
     * @desc 批量更新卡密记录
     * @return array success 是否成功
     * @return array count 更新数量
     */
    public function assignment() {
        $ids = $this->ids;
        $userInfo = null;
        
        if (isset($this->user_id) && !empty($this->user_id)) {
            $userInfo = \PhalApi\DI()->notorm->phalapi_user->where('id', $this->user_id)->fetchOne();
        }
        
        $data = array();
        if (isset($this->note) && !empty($this->note)) {
            $data['note'] = $this->note;
        }
        if (isset($this->user_id) && !empty($this->user_id)) {
            $data['user_id'] = $this->user_id;
        }
        //每张卡密都关联用户信息
        if ($userInfo && isset($userInfo['nickname'])) {
            $data['nickname'] = $userInfo['nickname'];
        }
        if ($userInfo && isset($userInfo['username'])) {
            $data['username'] = $userInfo['username'];
        }
        
        if (empty($data)) {
            throw new \PhalApi\Exception\BadRequestException('没有可更新的数据');
        }
        
        $count = \PhalApi\DI()->notorm->phone_kami
            ->where('id', $ids)
            ->update($data);
            
        \PhalApi\DI()->response->addResult('success', true);
        return array('success' => true, 'count' => $count);
    }

    /**
     * 使用卡密
     * @desc 批量更新卡密记录
     * @return array success 是否成功
     * @return array count 更新数量
     */
    public function used() {
        $card_codes = $this->card_codes;
        $phoneIds = $this->phoneIds;

        $phoneList = array();
        $cardList = array();

        foreach ($phoneIds as $index => $phoneId) {
            $device = \PhalApi\DI()->notorm->phone_list
                ->select('id,mobile,username,time_line')
                ->where('id', $phoneId)
                ->fetchOne();
            $userInfo = \PhalApi\DI()->notorm->phalapi_user
                ->select('username,nickname,Invitations')
                ->where('username', $device['username'])
                ->fetchOne();

            if($device){
                $card = \PhalApi\DI()->notorm->phone_kami
                    ->select('card_code,status,duration_type,username,user_id')
                    ->where('card_code', $card_codes[$index])
                    ->fetchOne();

                if($card){
                    if($card['status'] == 1){
                        throw new \PhalApi\Exception\BadRequestException('卡密已经被使用');
                    }

                    if($card['username'] != $device['username']){
                        throw new \PhalApi\Exception\BadRequestException('卡密与设备不匹配');
                    }

                    //把卡密设置为已经使用了
                    // $card['nickname'] = $userInfo['nickname'];
                    // $card['Invitations'] = $userInfo['Invitations'];
                    $card['status'] = 1;
                    $card['mobile'] = $device['mobile'];
                    $card['phone_id'] = $phoneId;
                    $card['used_time'] = date('Y-m-d H:i:s', time());
                    // $card['update_time'] = date('Y-m-d H:i:s', time());
                    $card['create_time'] = date('Y-m-d H:i:s', time());
                    $card['note'] = '已使用';
                    $update = \PhalApi\DI()->notorm->phone_kami
                        ->where('card_code', $card_codes[$index])
                        ->update($card);

                    $card['nickname'] = $userInfo['nickname'];
                    $card['Invitations'] = $userInfo['Invitations'];
                    //写上记录
                    \PhalApi\DI()->notorm->phone_kami_used->insert($card);
                    if($update){
                        // 计算新的有效期
                        // 获取当前时间戳
                        $currentTime = time();
                        // 计算有效天数对应的秒数（天数×24小时×60分钟×60秒）
                        $expireDays = (int)$card['duration_type'] * (24 * 60 * 60);
                        // 判断设备有效期：如果有未过期有效期则沿用，否则使用当前时间
                        if (!empty($device['time_line']) && strtotime($device['time_line']) >= $currentTime) {
                            $baseTimestamp = strtotime($device['time_line']);
                        } else {
                            $baseTimestamp = $currentTime;
                        }
                        // 生成新的有效期时间戳（基准时间+有效期秒数）
                        $newTimestamp = $baseTimestamp + ($expireDays);
                        // 转换为数据库存储的日期格式
                        $device['time_line'] = date('Y-m-d H:i:s', $newTimestamp);
                        $update = \PhalApi\DI()->notorm->phone_list
                            ->where('id', $phoneId)
                            ->update(array("time_line" => $device['time_line']));
                    }
                }
            }
            $phoneList[] = $device['mobile'];
            $cardList[] = $card['card_code'];
        }
        
        \PhalApi\DI()->response->addResult('success', true);
        return array('card_codes' => $cardList, 'phoneList' => $phoneList);
    }
}